<template>
  <div class="booking-statistics">
    <div class="header">
      <h2>{{ venueInfo.name }} - 按人头收费统计</h2>
      <div class="actions">
        <el-date-picker
          v-model="selectedDate"
          type="date"
          placeholder="选择日期"
          @change="loadStatistics"
        />
        <el-button type="primary">定价管理</el-button>
      </div>
    </div>

    <!-- 汇总卡片 -->
    <div class="summary-cards" v-if="dailySummary">
      <div class="card">
        <h4>总容量</h4>
        <span class="value">{{ dailySummary.total_capacity }}人</span>
      </div>
      <div class="card">
        <h4>已预订</h4>
        <span class="value">{{ dailySummary.total_booked }}人</span>
        <span class="rate">({{ dailySummary.average_occupancy_rate }}%)</span>
      </div>
      <div class="card">
        <h4>已到场</h4>
        <span class="value">{{ dailySummary.total_attended }}人</span>
        <span class="rate">({{ dailySummary.average_attendance_rate }}%)</span>
      </div>
      <div class="card">
        <h4>剩余名额</h4>
        <span class="value">{{ dailySummary.available_total }}人</span>
      </div>
    </div>

    <!-- 时段统计卡片 -->
    <div class="time-slots-grid">
      <div v-for="slot in hourlyStats" :key="slot.time_slot_id" class="time-slot-card">
        <div class="time-header">
          <span class="time-range">{{ slot.time_range }}</span>
          <span class="price">¥{{ slot.per_person_price }}</span>
        </div>
        <div class="capacity-info">
          <span class="capacity">{{ slot.capacity }}人</span>
        </div>
        <div class="booking-info">
          <div class="info-row">
            <span class="label">预订:</span>
            <span class="value">{{ slot.booked_count || 0 }}人</span>
          </div>
          <div class="info-row">
            <span class="label">到场:</span>
            <span class="value">{{ slot.attended_count || 0 }}人</span>
          </div>
        </div>
        <div class="actions">
          <el-button size="small" @click="handlePriceEdit(slot)">点击设置</el-button>
        </div>
        <div class="status-indicator" :class="{ 'full': slot.booked_count >= slot.capacity }">
          {{ slot.status === '爆满' ? '爆满' : '开放' }}
        </div>
      </div>
    </div>

    <!-- 价格编辑对话框 -->
    <el-dialog v-model="priceEditVisible" title="编辑价格" width="400px">
      <el-form :model="priceForm" label-width="120px">
        <el-form-item label="时间段">
          <el-input :value="priceForm.time_range" disabled />
        </el-form-item>
        <el-form-item label="每人价格">
          <el-input-number v-model="priceForm.per_person_price" :precision="2" :min="0" />
        </el-form-item>
        <el-form-item label="最小收费人数">
          <el-input-number v-model="priceForm.min_charge_count" :min="1" />
        </el-form-item>
        <el-form-item label="容量">
          <el-input-number v-model="priceForm.capacity" :min="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="priceEditVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePriceSave" :loading="saveLoading">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'

export default {
  name: 'BookingStatistics',
  setup() {
    const route = useRoute()
    const venueId = ref(parseInt(route.params.venueId))
    const loading = ref(false)
    const saveLoading = ref(false)
    const selectedDate = ref(new Date())
    const statisticsDate = ref('')
    const priceEditVisible = ref(false)
    
    const venueInfo = reactive({
      id: null,
      name: '测试场馆',
      max_capacity: 0
    })
    
    const dailySummary = ref(null)
    const hourlyStats = ref([])
    
    const priceForm = reactive({
      time_slot_id: null,
      time_range: '',
      per_person_price: 0,
      min_charge_count: 1,
      capacity: 1
    })
    
    const loadStatistics = async () => {
      loading.value = true
      try {
        const dateStr = selectedDate.value ? 
          selectedDate.value.toISOString().split('T')[0] : 
          new Date().toISOString().split('T')[0]
        
        // 调用真实的API
        const token = localStorage.getItem('token')
        const response = await fetch(`/api/v1/admin/venues/${venueId.value}/booking-statistics?date=${dateStr}`, {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
        })
        
        if (response.ok) {
          const data = await response.json()
          if (data.code === 200) {
            statisticsDate.value = data.data.statistics_date
            venueInfo.id = data.data.venue_info.id
            venueInfo.name = data.data.venue_info.name
            venueInfo.max_capacity = data.data.venue_info.max_capacity
            dailySummary.value = data.data.daily_summary
            hourlyStats.value = data.data.hourly_stats
          } else {
            ElMessage.error('获取统计数据失败: ' + data.message)
            // 如果没有数据，显示空数据
            dailySummary.value = {
              total_capacity: 0,
              total_booked: 0,
              total_attended: 0,
              available_total: 0,
              average_occupancy_rate: 0,
              average_attendance_rate: 0
            }
            hourlyStats.value = []
          }
        } else {
          ElMessage.error('获取统计数据失败: ' + response.statusText)
          // 如果没有数据，显示空数据
          dailySummary.value = {
            total_capacity: 0,
            total_booked: 0,
            total_attended: 0,
            available_total: 0,
            average_occupancy_rate: 0,
            average_attendance_rate: 0
          }
          hourlyStats.value = []
        }
        
      } catch (error) {
        console.error('API调用失败:', error)
        ElMessage.error('获取统计数据失败: ' + error.message)
        // 如果没有数据，显示空数据
        dailySummary.value = {
          total_capacity: 0,
          total_booked: 0,
          total_attended: 0,
          available_total: 0,
          average_occupancy_rate: 0,
          average_attendance_rate: 0
        }
        hourlyStats.value = []
      } finally {
        loading.value = false
      }
    }
    
    const handlePriceEdit = (row) => {
      priceForm.time_slot_id = row.time_slot_id
      priceForm.time_range = row.time_range
      priceForm.per_person_price = row.per_person_price
      priceForm.min_charge_count = row.min_charge_count
      priceForm.capacity = row.capacity
      priceEditVisible.value = true
    }
    
    const handlePriceSave = async () => {
      try {
        saveLoading.value = true
        // 模拟保存
        await new Promise(resolve => setTimeout(resolve, 1000))
        ElMessage.success('价格更新成功')
        priceEditVisible.value = false
        await loadStatistics()
      } catch (error) {
        ElMessage.error('价格更新失败')
      } finally {
        saveLoading.value = false
      }
    }
    
    onMounted(() => {
      loadStatistics()
    })
    
    return {
      venueId,
      loading,
      saveLoading,
      selectedDate,
      statisticsDate,
      venueInfo,
      dailySummary,
      hourlyStats,
      priceEditVisible,
      priceForm,
      loadStatistics,
      handlePriceEdit,
      handlePriceSave
    }
  }
}
</script>

<style scoped>
.booking-statistics {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #333;
}

.actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.summary-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  text-align: center;
}

.card h4 {
  margin: 0 0 10px 0;
  color: #666;
  font-size: 14px;
}

.card .value {
  display: block;
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.card .rate {
  font-size: 12px;
  color: #999;
}

.time-slots-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.time-slot-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  border: 2px solid #e0e6e9;
  position: relative;
  transition: all 0.3s ease;
}

.time-slot-card:hover {
  box-shadow: 0 4px 20px rgba(0,0,0,0.15);
  transform: translateY(-2px);
}

.time-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.time-range {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.price {
  font-size: 18px;
  font-weight: bold;
  color: #e74c3c;
}

.capacity-info {
  text-align: center;
  margin-bottom: 15px;
}

.capacity {
  font-size: 14px;
  color: #666;
  background: #f0f0f0;
  padding: 4px 8px;
  border-radius: 4px;
}

.booking-info {
  margin-bottom: 15px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.info-row .label {
  font-size: 14px;
  color: #666;
}

.info-row .value {
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

.actions {
  text-align: center;
  margin-bottom: 10px;
}

.status-indicator {
  position: absolute;
  top: 10px;
  right: 10px;
  background: #67c23a;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.status-indicator.full {
  background: #f56c6c;
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 15px;
  }
  
  .summary-cards {
    grid-template-columns: 1fr;
  }
  
  .time-slots-grid {
    grid-template-columns: 1fr;
  }
  
  .time-slot-card {
    margin-bottom: 15px;
  }
}
</style>
